package com.ash.other;

import com.ash.util.ConnectionUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @encoding : UTF-8
 * @Time : 2020/12/6 20:39
 * @Author : Chen Chao
 * @File : connection.com.ash.other.Test04.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 批处理
 */
public class Test04 {
    public static void main(String[] args) {
        String name="王五";
        int age=10;
        int count=10000;
        totalInsert(name, age,count);
    }

    private static void totalInsert(String name, int age,int count ) {

        Connection connection = ConnectionUtil.getConnection();
        String sql="insert into student (name,age) values (?,?)";
        PreparedStatement ps=null;
        try {
            ps = Objects.requireNonNull(connection).prepareStatement(sql);
            long l = System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                ps.setObject(1,name);
                ps.setObject(2,age);
                ps.executeUpdate();
            }
            System.out.println("逐条插入"+count+"条记录，共计时间为"+(System.currentTimeMillis()-l)+"ms");

            l=System.currentTimeMillis();
            for (int i = 0; i < count; i++) {
                ps.setObject(1,name);
                ps.setObject(2,age);
                /*上车*/
                ps.addBatch();
            }
            /*统一发车*/
            ps.executeBatch();
            System.out.println("批处理插入"+count+"条记录，共计时间为"+(System.currentTimeMillis()-l)+"ms");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            ConnectionUtil.close(connection,ps,null);
        }

    }
}
